using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;



namespace ArchSoft
{
    public partial class SearchFrm : Form
    {
        string folder = "";
        string path = "";
        string[] kq;
        string[] kq1;
        DataTable searchTable = new DataTable("Search");
        DataColumn col;
        DataRow row;
        
        string searchPath = "";

        string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
        int colIndex = -1;
        int rowIndex = -1;

       
        //FrmMain mainFrm = new FrmMain();
       // ProjectManager _manager;

        //FrmMain form = new FrmMain();
     //   public SearchFrm(string filename):base()
       // {
         //  InitializeComponent();
          // _manager = new ProjectManager(filename, this);
        //}

        public SearchFrm(string filename)
        {
            InitializeComponent();
            col = new DataColumn();
            col.DataType = System.Type.GetType("System.String");
            col.ColumnName = "Name";
            col.Caption = "Name";
            searchTable.Columns.Add(col);

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.String");
            col.ColumnName = "Date";
            col.Caption = "Date";
            searchTable.Columns.Add(col);

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.String");
            col.ColumnName = "Folder";
            col.Caption = "Folder";
            searchTable.Columns.Add(col);

            dataGridView1.DataSource = searchTable;

            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            this.mnuViewAutoCad.Click += new EventHandler(mnuViewAutoCad_Click);
            this.mnuViewDWG.Click +=new EventHandler(mnuViewDWG_Click);
            
        }

        void mnuViewAutoCad_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(dataGridView1[2, rowIndex].Value.ToString()+ Path.DirectorySeparatorChar + dataGridView1[0, rowIndex].Value.ToString());
                //  MessageBox.Show(dataGridView1[2, rowIndex].Value.ToString() + dataGridView1[0, rowIndex].Value.ToString());
            }
            catch (Exception ex)
            {
                
            }
        }

        void mnuViewDWG_Click(object sender, EventArgs e)
        {
            try
            {
                    string path = dataGridView1[2, rowIndex].Value.ToString() + Path.DirectorySeparatorChar + dataGridView1[0, rowIndex].Value.ToString();
                    //ViewDwgFrm view = new ViewDwgFrm(path);
                    //view.ShowDialog();
                    //ViewerMainForm frm = new ViewerMainForm();
                    //frm.FileName = path;
                    //frm.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }

        public string getPath()
        {
            return path;
        }

        public void setPath(string filename)
        {
            path = filename;
        }

        private void cmbFolder_SelectedIndexChanged(object sender, EventArgs e)
        {
            folder = cmbFolder.SelectedItem.ToString();

        }

        private void SearchFrm_Load(object sender, EventArgs e)
        {
            //MessageBox.Show(path + Path.DirectorySeparatorChar + "03 Output");
            string path1 = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + "03 Output";
            //MessageBox.Show(Directory.GetDirectories(path1).Length.ToString());
            labelElement.Text = "Element(s) : " + Directory.GetDirectories(path1).Length.ToString();
            labelName.Text = "PROJECT NAME : " + Path.GetFileNameWithoutExtension(path);
            labelFile.Text = "Total file(s) : " + Directory.GetFiles(Path.GetDirectoryName(path),"*.*",SearchOption.AllDirectories).Length.ToString();
        }

        

        

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {

                //MessageBox.Show(path);
                //MessageBox.Show(Path.GetDirectoryName(path));
                /*

               MessageBox.Show( Path.GetDirectoryName(path));
               MessageBox.Show( Path.GetExtension(path));
               MessageBox.Show( Path.GetFileName(path));
               MessageBox.Show( Path.GetFileNameWithoutExtension(path));
               MessageBox.Show( Path.GetFullPath(path));
               MessageBox.Show( Path.GetPathRoot(path));
               */
                //MessageBox.Show( path.Length.ToString());
                //MessageBox.Show( Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + folder);


                if (txtName.Text != "")
                {

                    string searchPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + folder;
                    //MessageBox.Show(Directory.Exists(searchPath).ToString());
                    //MessageBox.Show(searchPath);



                    string mau = "*" + txtName.Text + "*";

                    kq = Directory.GetDirectories(searchPath, mau, SearchOption.AllDirectories);

                    /*
                   for (int i = 0; i < kq.Length; i++)
                   {
                       //MessageBox.Show(kq[i].ToString());
                       txtResult.Text += kq[i] + Environment.NewLine;
                   }
                      */

                    kq1 = Directory.GetFiles(searchPath, mau, SearchOption.AllDirectories);

                    if ((kq.Length > 0) || (kq1.Length > 0))
                    {


                        /*
                       //for (int i = 0; i < kq1.Length; i++)
                       //{
                       //    //MessageBox.Show(kq1[i].ToString());
                       //    txtResult.Text += kq1[i] + Environment.NewLine;
                       //}
                       // */

                        // for (int i = 0; i < kq.Length; i++)
                        // {
                        //     listBoxSearch.Items.Add(Path.GetFileName(kq[i]));
                        // }

                        // for (int i = 0; i < kq1.Length; i++)
                        // {

                        //     listBoxSearch.Items.Add(Path.GetFileName(kq1[i]));
                        // }

                        // for (int i = 0; i < kq1.Length; i++)
                        // {
                        //     lstDirectory.Items.Add(Path.GetDirectoryName(kq1[i]));
                        // }

                        // for (int i = 0; i < kq.Length; i++)
                        // {
                        //     lstDirectory.Items.Add(Path.GetDirectoryName(kq[i]));
                        // }

                        // for (int i = 0; i < kq1.Length; i++)
                        // {
                        //     lstDate.Items.Add(Directory.GetCreationTime(kq1[i]).ToString());
                        // }

                        DataTable dt = new DataTable("Search");
                        for (int i = 0; i < kq1.Length; i++)
                        {
                            row = searchTable.NewRow();
                            row["Name"] = Path.GetFileName(kq1[i]);
                            row["Date"] = Directory.GetCreationTime(kq1[i]).ToString();
                            row["Folder"] = Path.GetDirectoryName(kq1[i]);
                            searchTable.Rows.Add(row);
                        }

                        dataGridView1.DataSource = searchTable;

                        dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

                       // statusStrip1.Items.Add("Location : " + folder);
                        //statusStrip1.Visible = true;

                        //statusStrip1.Items.Add(kq1.Length.ToString() + " files found");


                        //labelName.Text = "PROJECT NAME : " + Path.GetFileNameWithoutExtension(path);

                        toolStripStatusLabel1.Text = "Location : " + folder;
                        toolStripStatusLabel3.Text = kq1.Length.ToString() + " file(s) is found";

                        //labelElement.Text = "Element : " + Directory.GetDirectories(searchPath).Length.ToString();

                        
                        //labelFile.Text = "Total : " + Directory.GetFiles(searchPath).Length.ToString();
                    }
                    else
                    {
                        toolStripStatusLabel3.Text = kq1.Length.ToString() + " file(s) is found";
                    }
                }
                else
                {
                    MessageBox.Show("Please type KeyWord");
                }


                // //xu ly list view


                // string searchPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + folder;
                // string mau = "*" + txtName.Text + "*";

                // kq = Directory.GetDirectories(searchPath, mau, SearchOption.AllDirectories);
                // kq1 = Directory.GetFiles(searchPath, mau, SearchOption.AllDirectories);

                // /*
                // ColumnHeader columnHeader1 = new ColumnHeader();
                // columnHeader1.Text = "Name";
                // columnHeader1.TextAlign = HorizontalAlignment.Left;
                //// columnHeader1.Width = 146;

                // ColumnHeader columnHeader2 = new ColumnHeader();
                // columnHeader1.Text = "Date";
                // columnHeader1.TextAlign = HorizontalAlignment.Left;
                //// columnHeader1.Width = 146;

                // ColumnHeader columnHeader3 = new ColumnHeader();
                // columnHeader1.Text = "Folder";
                // columnHeader1.TextAlign = HorizontalAlignment.Left;
                // //columnHeader1.Width = 146;

                // this.listViewSearch.Columns.Add(columnHeader1);
                // this.listViewSearch.Columns.Add(columnHeader2);
                // this.listViewSearch.Columns.Add(columnHeader3);

                //  */

                // for (int i = 0; i < kq1.Length; i++)
                // {
                //     /*
                //     ListViewItem listItem1 = new ListViewItem(Path.GetFileName(kq1[i]));
                //     listItem1.SubItems.Add(Path.GetFileName(kq1[i]));

                //     ListViewItem listItem2 = new ListViewItem(Path.GetFileName(kq1[i]));
                //     listItem2.SubItems.Add(Path.GetDirectoryName(kq1[i]));

                //     ListViewItem listItem3 = new ListViewItem(Path.GetFileName(kq1[i]));
                //     listItem3.SubItems.Add(Directory.GetCreationTime(kq1[i]).ToString());

                //     listViewSearch.Items.Add(listItem1);
                //     listViewSearch.Items.Add(listItem2);
                //     listViewSearch.Items.Add(listItem3);
                //     */


                // }





                //for (int i = 0; i < kq1.Length; i++)
                //{
                //    row = searchTable.NewRow();
                //    row["Name"] = Path.GetFileName(kq1[i]);
                //    row["Date"] = Directory.GetCreationTime(kq1[i]).ToString();
                //    row["Folder"] = Path.GetDirectoryName(kq1[i]);
                //    searchTable.Rows.Add(row);
                //}

            }
            catch(Exception eee)
            {
                //MessageBox.Show(eee.Message);
                //MessageBox.Show(eee.StackTrace);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            /*
            listBoxSearch.Items.Clear();
            lstDirectory.Items.Clear();
            lstDate.Items.Clear();
            */
            try
            {
                searchTable.Rows.Clear();
                toolStripStatusLabel1.Text = "";
                toolStripStatusLabel3.Text = "";
                //dataGridView1.Rows.Clear();

                dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            catch (Exception eee)
            {
                MessageBox.Show(eee.Message);
            }
        }

       



        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(searchPath);
                searchPath = "";
            }
            catch(Exception eee)
            {
                MessageBox.Show(eee.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
            
        }
              

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
           //MessageBox.Show( dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString());
            try
            {
                searchPath = dataGridView1[2, e.RowIndex].Value.ToString() + Path.DirectorySeparatorChar + dataGridView1[0, e.RowIndex].Value.ToString();
            }
            catch (Exception eee)
            {
                //MessageBox.Show(eee.Message);
            }
            //System.Diagnostics.Process.Start(searchPath);
        }

        private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {         
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                searchPath = dataGridView1[2, e.RowIndex].Value.ToString() + Path.DirectorySeparatorChar + dataGridView1[0, e.RowIndex].Value.ToString();
                System.Diagnostics.Process.Start(searchPath);
            }
            catch (Exception eee)
            {
            }
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == "mnuOpen")
            {
                //MessageBox.Show(dataGridView1[2,rowIndex].Value.ToString());
                System.Diagnostics.Process.Start(dataGridView1[2, rowIndex].Value.ToString());
            }
        }

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                rowIndex = e.RowIndex;
                colIndex = e.ColumnIndex;

                string ex = Path.GetExtension(dataGridView1[0,e.RowIndex].Value.ToString());
                if (ex.IndexOf(".dwg") < 0)
                {
                    mnuOpenView.Visible = false;
                }
                else
                {
                    mnuOpenView.Visible = true;
                }
            }
        }

        private void SearchFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //AddAccessRuleAll();
        }

        public void AddAccessRule(string path)
        {
            DirectoryInfo dInfor = new DirectoryInfo(path);
            DirectorySecurity dSecurity = dInfor.GetAccessControl();
            dSecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, AccessControlType.Deny));
            dInfor.SetAccessControl(dSecurity);
        }

        public void RemoveAccessRule(string path)
        {
            DirectoryInfo dInfor = new DirectoryInfo(path);
            DirectorySecurity dSecurity = dInfor.GetAccessControl();

            dSecurity.RemoveAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, AccessControlType.Deny));
            dInfor.SetAccessControl(dSecurity);
        }

        public void RemoveAccessRuleAll()
        {
            try
            {
                string[] dir = Directory.GetDirectories(Directory.GetParent(path).ToString());
                for (int i = 0; i < dir.Length; i++)
                {
                    //MessageBox.Show(dir[i]);
                    RemoveAccessRule(dir[i]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void AddAccessRuleAll()
        {
            try
            {

                //foreach (string dir in Directory.GetDirectories(getFilePath()))
                //{
                //    MessageBox.Show(dir);
                //}

                // MessageBox.Show(getFilePath());

                string[] dir = Directory.GetDirectories(Directory.GetParent(path).ToString());
                for (int i = 0; i < dir.Length; i++)
                {
                    // MessageBox.Show(dir[i]);
                    AddAccessRule(dir[i]);
                }
                //string temp = Directory.GetParent(getFilePath()).ToString();
                //AddAccessRule(temp);
            }
            catch (Exception ex)
            {

            }
        }



        
    }
}